package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.MyResponseResult;
import com.itheima.utils.MyJwtUtils;
import com.itheima.utils.MyThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

//@WebFilter(urlPatterns = "/*")
//@Component
public class MyLoginFilter implements Filter {
//    @Autowired
    private MyJwtUtils myJwtUtils;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if("/login".equals(uri)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = request.getHeader("Token");
        Map<String, Object> map = myJwtUtils.parseJwt(token);
        if(map==null){
            MyResponseResult<Object> result = MyResponseResult.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(result);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.getWriter().print(jsonString);
            return;
        }
        //合法
        MyThreadLocalUtils.setValue(map);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
